//
//  ChatViewController.m
//  ChatDemo-UI3.0
//
//  Created by dhc on 15/6/26.
//  Change By WZZ on 16.8.26
//  Copyright (c) 2015年 easemob.com. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatDemoHelper.h"

#import "RomensSDK/WebRequestData.h"
#import "ChatGroupDetailViewController.h"
#import "ContactListSelectViewController.h"
//#import "StreamViewController.h"
#import "HXDDUserEntity.h"
#import "HXRuntimeStatus.h"
#import "EMChooseViewController.h"
#import "EaseMessageModel.h"
#import "EaseEmotionManager.h"
#import "EaseEmoji.h"
#import "RomensSDK/UIViewController+HUD.h"
@interface ChatViewController ()<UIAlertViewDelegate, EaseMessageViewControllerDelegate, EaseMessageViewControllerDataSource,EMClientDelegate,EMChooseViewDelegate>
{
    UIMenuItem *_copyMenuItem;
    UIMenuItem *_deleteMenuItem;
    UIMenuItem *_transpondMenuItem;
    UIButton *streamBtn; // 信息流
    UIView *badgeView;   // 小红点
    UILabel *numOfMessage; // 未读信息流条数
}

@property (nonatomic) BOOL isPlayingAudio;

@property (nonatomic) NSMutableDictionary *emotionDic;
@property (nonatomic, copy) EaseSelectAtTargetCallback selectedCallback;
@property (nonatomic, strong) UIView *networkStateView;

@end

@implementation ChatViewController


-(void)TitleDes
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableView.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1];
    
    if (self.conversation.type == EMConversationTypeChat) {
        if ([self.conversation.conversationId isEqualToString:@"001"]
            && [HXRuntimeStatus instance].systemServiceTitle)
            self.title = [HXRuntimeStatus instance].systemServiceTitle;
        else
        {
            HXDDUserEntity *user = [[HXRuntimeStatus instance] GetUserForName:self.conversation.conversationId];
            if (user) {
                self.title = user.nick;
            }else {
                self.title = self.conversation.conversationId;
            }
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendCallTexts:) name:@"sendcallmsg_wzz_16.11.9" object:nil];//电话相关
        }
    }
    else if (self.conversation.type == EMConversationTypeGroupChat) {
        if ([[self.conversation.ext objectForKey:@"subject"] length])
        {
            self.title = [self.conversation.ext objectForKey:@"subject"];
        }
    }
    
    
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;

    //父类中已写，但是需要重新设置父类中颜色。
    [[EaseBaseMessageCell appearance] setSendBubbleBackgroundImage:[[UIImage imageNamed:@"HuanXin.bundle/chat_sender_bg"] stretchableImageWithLeftCapWidth:5 topCapHeight:35]];
    [[EaseBaseMessageCell appearance] setRecvBubbleBackgroundImage:[[UIImage imageNamed:@"HuanXin.bundle/chat_receiver_bg"] stretchableImageWithLeftCapWidth:35 topCapHeight:35]];
    
    [[EaseBaseMessageCell appearance] setSendMessageVoiceAnimationImages:
  @[[UIImage imageNamed:@"HuanXin.bundle/chat_sender_audio_playing_full"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_sender_audio_playing_000"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_sender_audio_playing_001"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_sender_audio_playing_002"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_sender_audio_playing_003"]]];
    
    [[EaseBaseMessageCell appearance] setRecvMessageVoiceAnimationImages:
  @[[UIImage imageNamed:@"HuanXin.bundle/chat_receiver_audio_playing_full"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_receiver_audio_playing000"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_receiver_audio_playing001"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_receiver_audio_playing002"],
    [UIImage imageNamed:@"HuanXin.bundle/chat_receiver_audio_playing003"]]];
    
    [[EaseBaseMessageCell appearance] setAvatarSize:40.f];
    [[EaseBaseMessageCell appearance] setAvatarCornerRadius:20.f];
    [[EaseChatBarMoreView appearance] setMoreViewBackgroundColor:[UIColor colorWithRed:240 / 255.0 green:242 / 255.0 blue:247 / 255.0 alpha:1.0]];
    
    // 初始化界面上的按钮
//    [self _setupBarButtonItem];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteAllMessages:) name:KNOTIFICATIONNAME_DELETEALLMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitGroup) name:@"ExitGroup" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertCallMessage:) name:@"insertCallMessage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCallNotification:) name:@"callOutWithChatter" object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCallNotification:) name:KNOTIFICATION_CALL_CLOSE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showStrean) name:@"showStream_group" object:nil];
    
//    //通过会话管理者获取已收发消息//父类中已写，重复调用该方法，会导致对话的数据cell重复
    [self tableViewDidTriggerHeaderRefresh];
    
//测试，自己发送假的数据；
//    [self unreallySendMsg];
    [self networkStateView];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[EMClient sharedClient] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //对键盘的显示进行配置
//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    //发送通知，重新统计未读消息数量
    [[NSNotificationCenter defaultCenter] postNotificationName:@"setupUnreadMessageCount" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];

    [[EMClient sharedClient].chatManager removeDelegate:self];
    [[EMClient sharedClient].roomManager removeDelegate:self];
    [[ChatDemoHelper shareHelper] setChatVC:nil];
    
    if (self.deleteConversationIfNull) {
        //判断当前会话是否为空，若符合则删除该会话
        EMMessage *message = [self.conversation latestMessage];
        if (message == nil) {
            [[EMClient sharedClient].chatManager deleteConversation:self.conversation.conversationId isDeleteMessages:NO completion:nil];
        }
    }

}
#pragma mark - setup subviews
- (void)_setupLeftBarButtonItem
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"EaseUIResource.bundle/back"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
    self.navigationController.interactivePopGestureRecognizer.delegate = (id<UIGestureRecognizerDelegate>)self;

}
- (void)_setupRightBarButtonItem {
    //单聊
    if (self.conversation.type == EMConversationTypeChat) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"HuanXin.bundle/delete"] style:UIBarButtonItemStyleDone target:self action:@selector(deleteAllMessages:)];
    }else {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"HuanXin.bundle/own_center"] style:UIBarButtonItemStyleDone target:self action:@selector(showGroupDetailAction)];
        //        [self RedPoint];
    }

}
// 信息流：该功能暂时屏蔽
//- (void)showStrean:(id)sender
//{
//    [self.view endEditing:YES];
//    if (self.conversation.type == EMConversationTypeGroupChat) {
//        StreamViewController *streamController = [[StreamViewController alloc] initWithGroupId:self.conversation.conversationId];
//        [self.navigationController pushViewController:streamController animated:YES];
//    }
//}

// 预处理红点
//- (void)RedPoint
//{
//    badgeView.hidden = YES;
//    NSString *handle=@"GetTaskProgress";
//    // 序列化JSON 为PHPTable
//    NSMutableDictionary* hash=[NSMutableDictionary new];
//    NSString*userid= [HXRuntimeStatus instance].user.guid;
//    [hash setValue:self.conversation.conversationId forKey:@"GROUPID"];
//    [hash setValue:userid forKey:@"USERID"];
//    
//    // 访问中间层方法
//    [self Request:[HXSystemWebUrl stringByAppendingString:@"/handle"]  queryType:handle postData:hash success:^(id respone) {
//        
//        WebRequestData*data1=(WebRequestData*)respone;
//        if(data1.Error.length>0)
//        {
//            [self SHowMessage:data1.Error type:showError];
//            return ;
//        }
//        if ([data1.RequestData integerValue]) {
//            self->badgeView.hidden = NO;
//            self->numOfMessage.text = [NSString stringWithFormat:@"%@",data1.RequestData];
//        }
//    } showHud:NO];
//    
//}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex != buttonIndex) {
        self.messageTimeIntervalTag = -1;
        [self.conversation deleteAllMessages:nil];
        [self.dataArray removeAllObjects];
        [self.messsagesSource removeAllObjects];
        
        [self.tableView reloadData];
    }
}

#pragma mark - EaseMessageViewControllerDelegate

- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   canLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   didLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    id object = [self.dataArray objectAtIndex:indexPath.row];
    if (![object isKindOfClass:[NSString class]]) {
        EaseMessageCell *cell = (EaseMessageCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        [cell becomeFirstResponder];
        self.menuIndexPath = indexPath;
        
        if ([self.chatDelegate respondsToSelector:@selector(IM_messageViewController:messageType:)]) {
            NSArray *itemArray = [self.chatDelegate IM_messageViewController:self messageType:(NSInteger)cell.model.bodyType];
            [self.menuController setMenuItems:itemArray];
            [self.menuController setTargetRect:cell.bubbleView.frame inView:cell.bubbleView.superview];
            [self.menuController setMenuVisible:YES animated:YES];
            return YES;
        }
        [self _showMenuViewController:cell.bubbleView andIndexPath:indexPath messageType:cell.model.bodyType];
    }
    return YES;
}
//跳转到个人资料界面,若需要自定，在子类中实现
//- (void)messageViewController:(EaseMessageViewController *)viewController
//  didSelectAvatarMessageModel:(id<IMessageModel>)messageModel
//{
//        return;
//}

#pragma mark - EaseMessageViewControllerDataSource
//将EMMessage类型转换为符合<IMessageModel>协议的类型
- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController
                           modelForMessage:(EMMessage *)message
{
    id<IMessageModel> model = nil;
    model = [[EaseMessageModel alloc] initWithMessage:message];
    if ([model.nickname isEqualToString:@"001"] && [HXRuntimeStatus instance].systemServiceTitle) {
        model.nickname = [HXRuntimeStatus instance].systemServiceTitle;
        model.avatarImage = [HXRuntimeStatus instance].systemServiceImage;
    }
    else
    {
        for (HXDDUserEntity *user in [HXRuntimeStatus instance].ALLUsers)
        {
            if ([user.name isEqualToString:model.nickname]) {
                model.avatarImage = [UIImage imageNamed:@"HuanXin.bundle/chatListCellHead"];
                if (user.avatar)
                    model.avatarURLPath = user.avatar;
                model.nickname = user.nick;
                model.userId = user.guid;
            }
        }
    }
    return model;
}

//添加表情数据
- (NSArray*)emotionFormessageViewController:(EaseMessageViewController *)viewController
{
    NSMutableArray *emotions = [NSMutableArray array];
    for (NSString *name in [EaseEmoji allEmoji]) {
        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
        [emotions addObject:emotion];
    }
    EaseEmotion *temp = [emotions objectAtIndex:0];
    EaseEmotionManager *managerDefault = [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:temp.emotionId]];
    
//    NSMutableArray *emotionGifs = [NSMutableArray array];
//    _emotionDic = [NSMutableDictionary dictionary];
//    NSArray *names = @[@"icon_002",@"icon_007",@"icon_010",@"icon_012",@"icon_013",@"icon_018",@"icon_019",@"icon_020",@"icon_021",@"icon_022",@"icon_024",@"icon_027",@"icon_029",@"icon_030",@"icon_035",@"icon_040"];
//    NSArray *emorionName = @[@"哭",@"翩翩起舞",@"暗爽",@"跳舞",@"挥泪告别",@"星星",@"爱s你啦",@"睡觉觉",@"飞吻",@"你不行",@"醒醒吧",@"生日快乐",@"哼",@"不活啦",@"扭屁股",@"迪斯科"];
//    int index = 0;
//    for (NSString *name in names) {
//        index++;
//        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:emorionName[index-1] emotionId:[NSString stringWithFormat:@"em%d",(1000 + index)] emotionThumbnail:[NSString stringWithFormat:@"%@_cover",name] emotionOriginal:[NSString stringWithFormat:@"%@",name] emotionOriginalURL:@"" emotionType:EMEmotionGif];
//        [emotionGifs addObject:emotion];
//        [_emotionDic setObject:emotion forKey:[NSString stringWithFormat:@"em%d",(1000 + index)]];
//    }
//    EaseEmotionManager *managerGif= [[EaseEmotionManager alloc] initWithType:EMEmotionGif emotionRow:2 emotionCol:4 emotions:emotionGifs tagImage:[UIImage imageNamed:@"icon_002_cover"]];
    
//    return @[managerDefault,managerGif];
    return @[managerDefault];
}

- (BOOL)isEmotionMessageFormessageViewController:(EaseMessageViewController *)viewController
                                    messageModel:(id<IMessageModel>)messageModel
{
    BOOL flag = NO;
    if ([messageModel.message.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
        return YES;
    }
    return flag;
}

- (EaseEmotion*)emotionURLFormessageViewController:(EaseMessageViewController *)viewController
                                      messageModel:(id<IMessageModel>)messageModel
{
    NSString *emotionId = [messageModel.message.ext objectForKey:MESSAGE_ATTR_EXPRESSION_ID];
    EaseEmotion *emotion = [_emotionDic objectForKey:emotionId];
    if (emotion == nil) {
        emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:emotionId emotionThumbnail:@"" emotionOriginal:@"" emotionOriginalURL:@"" emotionType:EMEmotionGif];
    }
    return emotion;
}

- (NSDictionary*)emotionExtFormessageViewController:(EaseMessageViewController *)viewController
                                        easeEmotion:(EaseEmotion*)easeEmotion
{
    return @{MESSAGE_ATTR_EXPRESSION_ID:easeEmotion.emotionId,MESSAGE_ATTR_IS_BIG_EXPRESSION:@(YES)};
}
- (BOOL)messageViewControllerShouldMarkMessagesAsRead:(EaseMessageViewController *)viewController {
    return YES;
}
//获取未读消息
- (void)messageViewControllerMarkAllMessagesAsRead:(EaseMessageViewController *)viewController
{
    [[NSNotificationCenter defaultCenter] postNotificationName:UnReadMsgsNotificationName object:nil];
}

#pragma mark - EaseMob

#pragma mark - EMClientDelegate

- (void)didLoginFromOtherDevice
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

- (void)didRemovedFromServer
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

#pragma mark - action
//返回上一层
- (void)backAction
{
//    [[EMClient sharedClient].chatManager removeDelegate:self];
//    [[EMClient sharedClient].roomManager removeDelegate:self];
//    [[ChatDemoHelper shareHelper] setChatVC:nil];
    
//    if (self.deleteConversationIfNull) {
//        //判断当前会话是否为空，若符合则删除该会话
//        EMMessage *message = [self.conversation latestMessage];
//        if (message == nil) {
//            [[EMClient sharedClient].chatManager deleteConversation:self.conversation.conversationId isDeleteMessages:NO completion:nil];
//        }
//    }
    //记录当前对话已读的最后一条消息
    [self storeLastHasReadMessageToLocal];
    
    [self.navigationController popViewControllerAnimated:YES];
}
//展示组消息
- (void)showGroupDetailAction
{
    [self.view endEditing:YES];
    if (self.conversation.type == EMConversationTypeGroupChat) {
        ChatGroupDetailViewController *detailController = [[ChatGroupDetailViewController alloc] initWithGroupId:self.conversation.conversationId];
        detailController.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
        [self.navigationController pushViewController:detailController animated:YES];
    }
}//删除所有的消息
- (void)deleteAllMessages:(id)sender
{
    if (self.dataArray.count == 0) {
        [self showHint:NSLocalizedString(@"message.noMessage", @"no messages")];
        return;
    }
    
    if ([sender isKindOfClass:[NSNotification class]]) {
        NSString *groupId = (NSString *)[(NSNotification *)sender object];
        BOOL isDelete = [groupId isEqualToString:self.conversation.conversationId];
        if (self.conversation.type != EMConversationTypeChat && isDelete) {
            self.messageTimeIntervalTag = -1;
            [self.conversation deleteAllMessages:nil];
            [self.messsagesSource removeAllObjects];
            [self.dataArray removeAllObjects];
            
            [self.tableView reloadData];
            [self showHint:NSLocalizedString(@"message.noMessage", @"no messages")];
        }
    }
    else if ([sender isKindOfClass:[UIButton class]]){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"sureToDelete", @"please make sure to delete") delegate:self cancelButtonTitle:NSLocalizedString(@"cancel", @"Cancel") otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
        [alertView show];
    }
}
#pragma mark - forward message：转发文本消息
- (void)forwardTextMessage:(NSDictionary *)messageInfo
{
    EaseMessageModel *model = self.messageModel;
    
    if (self.messageModel.bodyType == EMMessageBodyTypeText) {
        EMMessage *message;
        if ([messageInfo valueForKey:@"ext"]) {
            message = [EaseSDKHelper sendTextMessage:model.text
                                                  to:[messageInfo valueForKey:@"name"]
                                         messageType:EMChatTypeChat
                                          messageExt:[messageInfo valueForKey:@"ext"]];
        } else {
            message = [EaseSDKHelper sendTextMessage:model.text
                                                  to:[messageInfo valueForKey:@"name"]
                                         messageType:EMChatTypeChat
                                          messageExt:nil];
        }
        
        __weak typeof(self) weakSelf = self;
        //发送消息
        [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *message, EMError *aError) {
            if (aError) {
                NSLog(@"sendMessage failed. aError:%@",aError.errorDescription);
            }
            if (!aError) {
                if (self.IsTranspondMenu) {
                    self.IsTranspondMenu = NO;
                    NSMutableArray *array = [NSMutableArray arrayWithArray:[self.navigationController viewControllers]];
                    ChatViewController *chatVC = [[ChatViewController alloc] initWithConversationChatter:message.conversationId conversationType:EMConversationTypeChat];
                    if ([array count] >= 3) {
                        [array removeLastObject];
                        [array removeLastObject];
                    }
                    [array addObject:chatVC];
                    [weakSelf.navigationController setViewControllers:array animated:YES];
                }
            }
        }];
    }
    
}
//转发名片信息
- (void)forwardCardMessage:(NSDictionary *)messageInfo
{
    EMMessage *message = [EaseSDKHelper sendTextMessage:@"[名片]"
                                                     to:[messageInfo valueForKey:@"name"]
                                            messageType:EMChatTypeChat
                                             messageExt:[messageInfo valueForKey:@"ext"]];
    [self _sendMessage:message];
}
#warning mark--后期可能加上图片等的转发，而不是只转发名片和文本
////转发：只有名片 和 文本可以转发
//- (void)transpondMenuAction:(id)sender
//{
//    self.IsTranspondMenu=YES;
//    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
//        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
//        MyConnectViewController *userlist = [[MyConnectViewController alloc] init];
//        
//        //获取转发需要的消息
//        userlist.isForward = YES;//标记为转发
//        self.messageModel = model;
//        NSString *currentName = [[EMClient sharedClient] currentUsername];
//        HXDDUserEntity *User = [[RuntimeStatus instance] GetUserForName:currentName];//获取当前帐号名字
//        NSString *time = [NSString stringWithFormat:@"%lld",self.messageModel.message.timestamp];//获取时间
//        
//        userlist.returnUserBlock=^(HXDDUserEntity *user){
//            NSString *toName = user.name;
//            NSLog(@"转发：\n translate ext = %@",[model.message valueForKey:@"ext"]);
//            if([model.message valueForKey:@"ext"])
//            {
//                //名片
//                if ([[model.message valueForKey:@"ext"] valueForKey:@"user_card"]) {
//                    NSString *user_name = [[model.message valueForKey:@"ext"] valueForKey:@"user_name"];
//                    NSString *user_phone = [[model.message valueForKey:@"ext"] valueForKey:@"user_phone"];
//                    NSDictionary *messageInfo = @{@"name":toName,@"ext":@{@"user_card":@true,@"user_name": user_name,@"user_phone":user_phone},@"IstranspondMenu":@"yes"};
//                    NSLog(@"转发的详细信息：%@",messageInfo);
//                    
//                    [self forwardCardMessage:messageInfo];
//                }
//                //对转发过的文本信息
//                if ([[model.message valueForKey:@"ext"] valueForKey:MESSAGE_TRANSMIT]) {
//                    //                    NSDictionary *extDic = [model.message valueForKey:@"ext"];
//                    NSDictionary *extDic = @{MESSAGE_TRANSMIT:@"1",MESSAGE_FROM_ID:self.messageModel.message.from,MESSAGE_FROM_TIME:time};
//                    NSDictionary *messageInfo = @{@"name":toName,@"ext":extDic};
//                    NSLog(@"转发过的消息:%@\n",messageInfo);
//                    [self forwardTextMessage:messageInfo];
//                }
//            }
//            else
//            {   //对未转发过的文本进行转发
//                
//                //设置拓展属性ext
//                NSDictionary *extDic = @{MESSAGE_TRANSMIT:@"1",MESSAGE_FROM_ID:self.messageModel.message.from,MESSAGE_FROM_TIME:time};
//                NSDictionary *messageInfo = [NSDictionary new];
//                if ([User.nick isEqualToString:model.nickname]) {//判断是否来自自己
//                    messageInfo = @{@"name":toName};
//                } else {
//                    messageInfo = @{@"name":toName,@"ext":extDic};
//                }
//                
//                [self forwardTextMessage:messageInfo];
//            }
//        };
//        userlist.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:nil action:nil];
//        [self.navigationController pushViewController:userlist animated:YES];
//    }
//    self.menuIndexPath = nil;
//}
//拷贝复制
- (void)copyMenuAction:(id)sender
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        pasteboard.string = model.text;
    }
    
    self.menuIndexPath = nil;
}
//删除
- (void)deleteMenuAction:(id)sender
{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        NSMutableIndexSet *indexs = [NSMutableIndexSet indexSetWithIndex:self.menuIndexPath.row];
        NSMutableArray *indexPaths = [NSMutableArray arrayWithObjects:self.menuIndexPath, nil];
        
        [self.conversation deleteMessageWithId:model.message.messageId error:nil];
        [self.messsagesSource removeObject:model.message];
        
        if (self.menuIndexPath.row - 1 >= 0) {
            id nextMessage = nil;
            id prevMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row - 1)];
            if (self.menuIndexPath.row + 1 < [self.dataArray count]) {
                nextMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row + 1)];
            }
            if ((!nextMessage || [nextMessage isKindOfClass:[NSString class]]) && [prevMessage isKindOfClass:[NSString class]]) {
                [indexs addIndex:self.menuIndexPath.row - 1];
                [indexPaths addObject:[NSIndexPath indexPathForRow:(self.menuIndexPath.row - 1) inSection:0]];
            }
        }
        
        [self.dataArray removeObjectsAtIndexes:indexs];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        
        if ([self.dataArray count] == 0) {
            self.messageTimeIntervalTag = -1;
        }
    }
    
    self.menuIndexPath = nil;
}

#pragma mark - notification
- (void)exitGroup
{
    [self.navigationController popToViewController:self animated:NO];
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark -- call
//载入通话消息的通知
- (void)insertCallMessage:(NSNotification *)notification
{
    id object = notification.object;
    if (object) {
        EMMessage *message = (EMMessage *)object;
        [self addMessageToDataSource:message progress:nil];
        [[EMClient sharedClient].chatManager importMessages:@[message] completion:nil];
    }
}
//通话开始和通话结束
- (void)handleCallNotification:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        //开始call
        self.isViewDidAppear = NO;
    } else {
        //结束call
        self.isViewDidAppear = YES;
        //结束call会返回当前的挂断状况 object为数组
        if ([object isKindOfClass:[NSArray class]]) {
//            [self sendEndCallMsg:object];
        }
    }
}
//对发送的信息 进行处理
- (void)sendCallTexts:(NSNotification *)notification {
    id object = notification.object;
    if ([object isKindOfClass:[NSString class]]) {
        [self sendCallMsg:object];
    }
}
//#pragma mark--发送已读、状态为发送成功的 消息－－－－call
//假发送消息
- (void)sendCallMsg:(NSString *)text {
    if (isEmptyString(text)) {
        text = @"对方可能不在线";
    }
    EMMessage *message = [EaseSDKHelper sendTextMessage:text to:self.conversation.conversationId messageType:EMChatTypeChat messageExt:nil];
    //    message.isRead = YES;
    message.isDeliverAcked = YES;
    message.status = EMMessageStatusSuccessed;
    //获取当前的会话
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.conversation.conversationId type:EMConversationTypeChat createIfNotExist:YES];
    NSLog(@"chart最后一句话：%@",text);
    //插入一条消息到会话尾部
    [conversation appendMessage:message error:nil];
    //刷新当前界面的消息
    [self addMessageToDataSource:message progress:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"reload_wzz_16.11.10" object:nil];
    //    NSLog(@"最后一句话：%@",conversation.latestMessage);
}
#pragma mark - private
//创建 删除 复制 转发功能
- (void)_showMenuViewController:(UIView *)showInView
                   andIndexPath:(NSIndexPath *)indexPath
                    messageType:(EMMessageBodyType)messageType
{
    if (self.menuController == nil) {
        self.menuController = [UIMenuController sharedMenuController];
    }
    
    if (_deleteMenuItem == nil) {
        _deleteMenuItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"delete", @"Delete") action:@selector(deleteMenuAction:)];
    }
    
    if (_copyMenuItem == nil) {
        _copyMenuItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"copy", @"Copy") action:@selector(copyMenuAction:)];
    }
    
//    if (_transpondMenuItem == nil) {
//        _transpondMenuItem = [[UIMenuItem alloc] initWithTitle:NSLocalizedString(@"transpond", @"Transpond") action:@selector(transpondMenuAction:)];
//    }
    if (messageType == EMMessageBodyTypeText) {
//        [self.menuController setMenuItems:@[_copyMenuItem, _deleteMenuItem,_transpondMenuItem]];
        [self.menuController setMenuItems:@[_copyMenuItem, _deleteMenuItem]];
    }else {
        [self.menuController setMenuItems:@[_deleteMenuItem]];
    }
    [self.menuController setTargetRect:showInView.frame inView:showInView.superview];
    [self.menuController setMenuVisible:YES animated:YES];
}
#pragma mark - getter
- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"EaseUIResource.bundle/messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"network.disconnection", @"Network disconnection");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}
- (void)isConnect:(BOOL)isConnect{
    if (!isConnect) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
    
}
- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == EMConnectionDisconnected) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
}

#pragma mark ---- 聊天：自定义cell------
//用户根据messageModel判断是否显示自定义cell,返回nil显示默认cell,否则显示用户自定义cell
- (UITableViewCell *)messageViewController:(UITableView *)tableView
                       cellForMessageModel:(id<IMessageModel>)messageModel {

    if(self.chatDelegate && [self.chatDelegate respondsToSelector:@selector(IM_messageViewController:cellForMessageModel:)])
    {
        UITableViewCell *cell = [self.chatDelegate IM_messageViewController:tableView cellForMessageModel:(RM_MessageModel *)messageModel];
        if (cell) {
            return cell;
        }
    }
    return nil;
}
- (CGFloat)messageViewController:(EaseMessageViewController *)viewController
           heightForMessageModel:(id<IMessageModel>)messageModel
                   withCellWidth:(CGFloat)cellWidth {
    CGFloat tmpHeight = 0;
    if ([messageModel.messageId isEqualToString:GetUserDefaults(messageModel.message.conversationId)]) {
        tmpHeight = 20;
    }
    if (self.chatDelegate && [self.chatDelegate respondsToSelector:@selector(IM_messageViewController:heightForMessageModel:withCellWidth:)]) {
        CGFloat heigth = [self.chatDelegate IM_messageViewController:(ChatViewController *)viewController heightForMessageModel:(RM_MessageModel *)messageModel withCellWidth:cellWidth];
        if (heigth) {
            return heigth+tmpHeight;
        }
    }
    return 0.f;
}
//选中消息时的回调
- (BOOL)messageViewController:(EaseMessageViewController *)viewController
        didSelectMessageModel:(id<IMessageModel>)messageModel {
    
    if (self.chatDelegate && [self.chatDelegate respondsToSelector:@selector(IM_messageViewController:didSelectMessageModel:)])
    {
        BOOL value = [self.chatDelegate IM_messageViewController:(ChatViewController *)viewController didSelectMessageModel:(RM_MessageModel *)messageModel];
        if (value) {
            return value;
        }
    }
    return NO;
}
#pragma mark--用来发送假发送消息，以查看自定义cell的效果。
//假发送消息
- (void)unreallySendMsg:(NSString *)ext{
    EMMessage *message = [EaseSDKHelper sendTextMessage:@"我是假的数据" to:self.conversation.conversationId messageType:EMChatTypeChat messageExt:nil];
    //    message.isRead = YES;
    message.isDeliverAcked = YES;
    //    message.status = EMMessageStatusSuccessed;
    message.ext = @{@"ext":ext};
    //获取当前的会话
    EMConversation *conversation = [[EMClient sharedClient].chatManager getConversation:self.conversation.conversationId type:EMConversationTypeChat createIfNotExist:YES];
    NSLog(@"最后一句话：%@",conversation.latestMessage);
    //插入一条消息到会话尾部
    [conversation appendMessage:message error:nil];
    
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"reload_wzz_16.11.10" object:nil];
    //    //刷新当前界面的消息
    //    [self addMessageToDataSource:message progress:nil];
    //    NSLog(@"最后一句话：%@",conversation.latestMessage);
}

#pragma mark -- 记录当前对话已读的最后一条消息
- (void)storeLastHasReadMessageToLocal {
    if (self.dataArray.count > 0) {
        id object = [self.dataArray lastObject];
        if (![object isKindOfClass:[NSString class]]) {//安全性判断
            id<IMessageModel> model = object;
            NSString *key = model.message.conversationId;
            NSString *value = model.messageId;
            [[NSUserDefaults standardUserDefaults] setObject:value forKey:key];
        }
    }else {
        NSString *key = self.conversation.conversationId;
        [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:key];
    }
}

@end
